package com.tianhui.consignortwofei.mvp.ui.activity.editPicture;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bm.library.PhotoView;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.imageView.PictureDialog;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.DateUtil;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.StringUtil;
import com.fgs.common.widget.TabSwitchView;
import com.fgs.common.widget.itemView.InputItemView;
import com.fgs.common.widget.itemView.SettingItemView;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.DisplayPictureInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailPictureInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderUploadPictureActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.DisplayPictureAdapter;
import com.tianhui.consignortwofei.utils.Transform;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.configure.TimePickerType;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;
import com.xuexiang.xutil.common.StringUtils;

import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/2
 * @description 修改图片
 **/
public class EditOrderPictureActivity extends OrderUploadPictureActivity {

    @BindView(R.id.activity_order_loading_placeInputItemView)
    InputItemView mPlaceInputItemView;
    @BindView(R.id.activity_order_loading_weightInputItemView)
    InputItemView mWeightInputItemView;
    @BindView(R.id.activity_order_loading_tradWeightInputItemView)
    InputItemView mTradWeightInputItemView;
    @BindView(R.id.activity_order_loading_timeSettingItemView)
    SettingItemView mTimeSettingItemView;
    @BindView(R.id.activity_order_loading_typeTabSwitchView)
    TabSwitchView mTypeTabSwitchView;
    @BindView(R.id.activity_order_loading_imageView)
    PhotoView mImageView;
    @BindView(R.id.activity_order_loading_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.activity_order_loading_vehicleImageRecyclerView)
    RecyclerView mVehicleImageRecyclerView;
    @BindView(R.id.item_detail_picture_recyclerView)
    RecyclerView mPictureRecyclerView;

    TimePickerView mTimePickerView;
    private String mType = "1";

    private OrderModel mOrderModel;
    private DisplayPictureAdapter pictureAdapter;
    private PictureDialog pictureDialog;
    private GeoCoder mGeoCoder;

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_order_picture;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {

        super.init();
        setTitle("修改图片");
        mOrderModel = new OrderModel();

        mGeoCoder = GeoCoder.newInstance();
        mGeoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult == null && reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    showToast("抱歉，未找到结果");
                    return;
                }
//                LogUtil.print(JsonUtil.toJson(reverseGeoCodeResult));
                String resultAddress = reverseGeoCodeResult.getAddress();
                String resultDescription = reverseGeoCodeResult.getSematicDescription();
//                if (TextUtils.isEmpty(resultAddress) && TextUtils.isEmpty(resultDescription)) {
                if (TextUtils.isEmpty(resultAddress) && TextUtils.isEmpty(resultDescription)) {
                    return;
                }

                String address = resultAddress + resultDescription;
//                String address = resultAddress;

                mPlaceInputItemView.setContent(address);
            }
        });

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            String dispatchNo = bundle.getString(KeyValue.KEY_DISPATCH_NO);
            requestOrderDetailInfo(dispatchNo);
        }

        pictureAdapter = new DisplayPictureAdapter(this);
        pictureAdapter.setNeedEdit(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        mPictureRecyclerView.setLayoutManager(gridLayoutManager);
        mPictureRecyclerView.setAdapter(pictureAdapter);


        pictureAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                DisplayPictureInfo displayPictureInfo = pictureAdapter.getAllData().get(position);
                if (!TextUtils.isEmpty(displayPictureInfo.imageId)) {
                    pictureDialog = new PictureDialog(EditOrderPictureActivity.this);
                    pictureDialog.setCanSavePicture(true);
                    pictureDialog.setImageId(displayPictureInfo.imageId);
                    pictureDialog.show();
                } else {
                    showToast("暂无相关图片");
                }

//                if (!TextUtils.isEmpty(displayPictureInfo.imageId)) {
//                    String[] strings = displayPictureInfo.imageId.split(",");
//                    int length = strings.length;
//                    List<String> list = new ArrayList<>();
//                    for (int i = 0; i < length; i++) {
//                        list.add(Config.baseImageUrl + strings[i]);
//                    }
//                    pictureDialog.setImageUrlList(list);
//                }

            }
        });


        initListener();
    }

    private void requestOrderDetailInfo(String dispatchNo) {
        if (!TextUtils.isEmpty(dispatchNo)) {
            Map<String, String> map = new HashMap<>();
            map.put("dispatchno", dispatchNo);
            mOrderModel.orderSourceInfoModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<OrderInfo>>() {
                @Override
                public void onNext(CommonResponse<OrderInfo> commonResponse) {
                    if (commonResponse.getCode() == 20000) {
                        mOrderInfo = commonResponse.getData();
                        //刷新时不需要改变的
                        if (TextUtils.isEmpty(mOrderId)) {
                            mTimeSettingItemView.setContent(mOrderInfo.trantime);
                            mPlaceInputItemView.setContent(mOrderInfo.tranplace);
//                            geoCoder(getLatLng(mOrderInfo.tranlatitude, mOrderInfo.tranlongitude));
                        }
                        mOrderId = mOrderInfo.dispatchno;
                        setPictureImage(mOrderInfo);

                    } else {
                        showToast(commonResponse.getMsg());
                    }

                }

                @Override
                public void onError(ExceptionHandle.ResponseThrowable e) {
                    showToast(e.message);
                }
            });
        }
    }

    private LatLng getLatLng(String latitude, String longitude) {
        if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
            latitude = new BigDecimal(latitude).toString();
            longitude = new BigDecimal(longitude).toString();
            double latitudeLong = StringUtils.toDouble(latitude);
            double longitudeLong = StringUtils.toDouble(longitude);
            LatLng latLng;
            if (StringUtil.compareTwoString(longitude, "200") == 1 && StringUtil.compareTwoString(latitude, "80") == 1) {
                latitudeLong = latitudeLong / 600000;
                longitudeLong = longitudeLong / 600000;
                latLng = Transform.wgs84tobd09(longitudeLong, latitudeLong);
                LogUtil.print("标准经纬度");
            } else {
                latLng = new LatLng(latitudeLong, longitudeLong);
                LogUtil.print("百度经纬度");
            }

            return latLng;
        }
        return null;
    }

    private void geoCoder(LatLng latLng) {
        if (latLng == null) return;
        ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption()
                .location(latLng)
                .newVersion(1)
                .radius(200);
        mGeoCoder.reverseGeoCode(reverseGeoCodeOption);
    }


    private void setPictureImage(OrderInfo orderInfo) {
        if (orderInfo != null) {
            pictureAdapter.clear();
            DetailPictureInfo pictureInfo;
            pictureInfo = new DetailPictureInfo();
            pictureInfo.list = new ArrayList<>();
            DisplayPictureInfo displayPictureInfo;
            displayPictureInfo = new DisplayPictureInfo();
            displayPictureInfo.title = "装车回单";
            displayPictureInfo.imageId = orderInfo.poundimg;
//        displayPictureInfo.imageId = "8238,8239,8240,8241";
            pictureInfo.list.add(displayPictureInfo);

            displayPictureInfo = new DisplayPictureInfo();
            displayPictureInfo.title = "卸车回单";
            displayPictureInfo.imageId = orderInfo.recepitbill;
            pictureInfo.list.add(displayPictureInfo);

            displayPictureInfo = new DisplayPictureInfo();
            displayPictureInfo.title = "装车车辆";
            displayPictureInfo.imageId = orderInfo.loadingimg;
            pictureInfo.list.add(displayPictureInfo);

            displayPictureInfo = new DisplayPictureInfo();
            displayPictureInfo.title = "卸车车辆";
            displayPictureInfo.imageId = orderInfo.unloadimg;
            pictureInfo.list.add(displayPictureInfo);

            pictureAdapter.addAll(pictureInfo.list);
        }

    }

    private void initListener() {
        mTypeTabSwitchView.setOnTabCheckedChangeListener(new TabSwitchView.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int position, String item, String value) {
                mType = value;
                if (position == 0) {
                    mTimeSettingItemView.setContent(mOrderInfo.trantime);
//                    geoCoder(getLatLng(mOrderInfo.tranlatitude, mOrderInfo.tranlongitude));
                    mPlaceInputItemView.setContent(mOrderInfo.tranplace);
                } else {
                    mTimeSettingItemView.setContent(mOrderInfo.recelvetime);
//                    geoCoder(getLatLng(mOrderInfo.recelveatitude, mOrderInfo.recelvelongitude));
                    mPlaceInputItemView.setContent(mOrderInfo.receiveplace);
                }
                clearSelectPicture();

            }
        });
    }


    @Override
    public RecyclerView getVehicleImageRecyclerView() {
        return mVehicleImageRecyclerView;
    }

    @Override
    public RecyclerView getInvoicesImageRecyclerView() {
        return mRecyclerView;
    }

    @Override
    public String getAddress() {
        return mPlaceInputItemView.getContent();
    }

    @Override
    public String getTime() {
        return mTimeSettingItemView.getContent();
    }

    @OnClick(R.id.activity_order_loading_locationTextView)
    public void getDriverCommitLocation() {
        if (mType.equals("1")) {
//            mPlaceInputItemView.setContent(mOrderInfo.tranplace);
            geoCoder(getLatLng(mOrderInfo.tranlatitude, mOrderInfo.tranlongitude));
        } else {
//            mPlaceInputItemView.setContent(mOrderInfo.receiveplace);
            geoCoder(getLatLng(mOrderInfo.recelveatitude, mOrderInfo.recelvelongitude));
        }
    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

    @OnClick(R.id.activity_order_loading_placeTextView)
    public void openMap() {

//        checkPermission();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1 && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null && !bundle.isEmpty()) {
                String place = bundle.getString(KeyValue.KEY_PLACE);
                if (!TextUtils.isEmpty(place)) {
                    mPlaceInputItemView.setContent(place);
                    mPlaceInputItemView.getEditTextView().setSelection(place.length());
                }
            }

        }
    }

    @OnClick(R.id.activity_order_loading_timeSettingItemView)
    public void selectTime() {
        hideKeyboard();
        if (mTimePickerView == null) {
            mTimePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelected(Date date, View v) {
                    String string = DateUtil.getStandardTime(date.getTime(), "yyyy-MM-dd HH:mm:ss");
                    mTimeSettingItemView.setContent(string);
                }
            })
                    .setType(TimePickerType.ALL)
                    .setTitleText("请选择司磅时间")
                    .build();
        }
        mTimePickerView.show();
    }

    @OnClick(R.id.activity_order_loading_commitButton)
    public void commit() {
//        String grabWeight = mTradWeightInputItemView.getContent();
//        if (TextUtils.isEmpty(grabWeight)) {
//            showToast("获取抢单重量失败，请重新打开界面");
//            return;
//        }

        String place = mPlaceInputItemView.getContent();

        String weight = mWeightInputItemView.getContent();

        String time = mTimeSettingItemView.getContent();


//        if (TextUtils.isEmpty(weight)) {
//            showToast(R.string.tip_input_loading_weight);
//            return;
//        }
//
//        if (StringUtils.toDouble(weight) == 0) {
//            showToast(R.string.tip_loading_weight_can_not_zero);
//            return;
//        }
//
//
//        if (StringUtil.compareTwoString(weight, grabWeight) == 1) {
//            showToast(R.string.tip_can_not_greater_than_grab_weight);
//            return;
//        }
        if (TextUtils.isEmpty(mOrderId)) {
            showToast("未获取到订单号");
            return;
        }

        if (TextUtils.isEmpty(place)) {
            showToast(R.string.tip_input_weigh_man_place);
            return;
        }


        if (TextUtils.isEmpty(time)) {
            showToast(R.string.tip_select_weigh_man_time);
            return;
        }

        String selectVehiclePictureId = getVehicleImageId();
        if (TextUtils.isEmpty(selectVehiclePictureId)) {
//            showToast(R.string.tip_select_loading_weight_vehicle_image);
//            return;
            if (mType.equals("1")) {
                selectVehiclePictureId = mOrderInfo.loadingimg;
            } else {
                selectVehiclePictureId = mOrderInfo.unloadimg;
            }
        }


        String selectPictureId = getInvoicesImageId();
        if (TextUtils.isEmpty(selectPictureId)) {
//            showToast(R.string.tip_select_loading_weight_receipts);
//            return;
            if (mType.equals("1")) {
                selectPictureId = mOrderInfo.poundimg;
            } else {
                selectPictureId = mOrderInfo.recepitbill;
            }
        }


//        @Column(columnDefinition = "VARCHAR(100) COMMENT '装车经度'")
//        private String tranlongitude;
//        @Column(columnDefinition = "VARCHAR(100) COMMENT '装车纬度'")
//        private String tranlatitude;
//        @Column(columnDefinition = "VARCHAR(50) COMMENT '装货地市编号'")
//        private String delivercitycode;
//        @Column(columnDefinition = "VARCHAR(50) COMMENT '装货地市'")
//        private String delivercity;
//        if (isHasLocationInfo()) {
        Map<String, String> map = new HashMap<>();
        map.put("dispatchno", mOrderId);
        map.put("poundimg", selectPictureId);
        map.put("loadingimg", selectVehiclePictureId);
        map.put("poundpalce", place);
        map.put("poundtime", time);
        map.put("type", mType);//1装车，2卸货
//            requestConfirmLoading(AppUtils.generateRequestBody(map));
        requestConfirmLoading(map);

//        }


    }

    //    private void requestConfirmLoading(Map<String, RequestBody> map) {
    private void requestConfirmLoading(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            showToast("获取装车信息失败，请重新进入当前界面");
            return;
        }
        mOrderModel.confirmLoadingChangePictureModel(this, map, true, this.bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
//                    EventBusManage.refreshOrderList();
                    EventBusManage.refreshOrderDetail();
                    showConfirmDialog();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void showConfirmDialog() {
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("装货成功")
                .positiveText("查看")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        requestOrderDetailInfo(mOrderId);
                    }
                })
                .negativeText("返回")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                })
                .canceledOnTouchOutside(false)
                .cancelable(false)
                .show();
    }


    @Override
    protected void onDestroy() {
        if (mGeoCoder != null) {
            mGeoCoder.destroy();
        }
        super.onDestroy();

    }

}
